package com.tz.fruit.dao.impl;

import com.tz.fruit.dao.IAddressDao;
import com.tz.fruit.entity.Address;
import com.tz.fruit.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by asus on 2017/7/20.
 */
@Repository
@Transactional
public class AddressDaoImpl implements IAddressDao{

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(Address address) {
        getSession().save(address);
    }

    @Override
    public void deleteById(Long id) {
        Address addr = (Address) getSession().get(Address.class,id);
        if (null!=addr){
            getSession().delete(addr);
        }
    }

    @Override
    public Address findById(Long id) {
        return (Address) getSession().get(Address.class,id);
    }

    @Override
    public List<Address> findAll(Long userId) {
        return getSession().createQuery("from Address where userId=?").setParameter(0,userId).list();
    }

    @Override
    public List<Address> findByUserId(Long userId) {
        return (List<Address>) getSession().createCriteria(Address.class,"addr").add(Restrictions.eq("user.userId",userId)).list();
    }

    @Override
    public void update(Address address) {
        Address addr = (Address) getSession().get(Address.class,address.getAddressId());
        if(addr!=null){
            getSession().clear();
            getSession().update(address);
        }
    }
}
